package mychat.dao.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mychat.dao.MessageDao;
import mychat.vo.Message;
import mychat.vo.Msg;

public class MessageDaoImp implements MessageDao{
	
	private Connection con;
	public MessageDaoImp(Connection con){
		this.con=con;
	}

	public Connection getConnection() {
		// TODO Auto-generated method stub
		return con;
	}


	public List<Message> findAll() throws SQLException {
		ArrayList<Message> list=null;
        PreparedStatement preStat=null;
        ResultSet rs=null;
        String sql="select * from `message`";
        try{
            preStat = ( PreparedStatement )con.prepareStatement(sql);
            rs=preStat.executeQuery();
            list=new ArrayList<Message>();
            while(rs.next()){
                Message msg=new Msg(rs.getString("from"),rs.getString("to"),
                		rs.getInt("type"),rs.getString("content"));
                msg.setId(rs.getInt("id"));
                msg.setDate(rs.getTimestamp("date"));
                list.add(msg);
            }
        } catch (SQLException e){
            throw e;
        } finally {
        	if(!rs.isClosed()){
        		rs.close();
        		rs=null;
        	}
            if(!preStat.isClosed() ){
                preStat.close();
                preStat=null;
            }
        }
        return list;
	}

	
	public boolean doInsert(Message message) throws SQLException {
		boolean flag=false;
        PreparedStatement preStat=null;
        String sql="insert into `message` (`from`,`to`,`type`,`content`,`date`) values (?,?,?,?,?)";
        try{
            preStat = ( PreparedStatement )con.prepareStatement(sql);
            preStat.setString(1, message.getFrom());
            preStat.setString(2, message.getTo());
            preStat.setInt(3, message.getType());
            preStat.setString(4, message.getContent());
            preStat.setTimestamp(5, new java.sql.Timestamp(message.getDate().getTime()));
            if(preStat.executeUpdate() > 0){
                flag=true;
            }
        } catch (SQLException e){
            throw e;
        } finally {
            if(!preStat.isClosed() ){
                preStat.close();
                preStat=null;
            }
        }
        return flag;
	}

	
	public boolean doDelete(Message message) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

}
